package com.ytktt.study.week8.task6.shardingsphere.atomikosxa.service.impl;

import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.entity.item.ItemStockEntity;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.mapper.item.ItemMapper;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.mapper.item.ItemStockMapper;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.service.ItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品服务业务逻辑实现
 *
 * @author ytk
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {

    private final ItemMapper itemMapper;
    private final ItemStockMapper itemStockMapper;

    @Override
    public ItemStockEntity getItemStock(int itemId) {
        return this.itemStockMapper.selectByItemId(itemId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ShardingSphereTransactionType(TransactionType.LOCAL)
    public boolean decreItemStock(int itemId, int amount) {
        int result = this.itemMapper.updateSales(itemId, amount);
        result = result * this.itemStockMapper.updateDecreStock(itemId, amount);
        return result == 1;
    }
}
